package com.etennis.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etennis.pojos.PageRequest;
import com.etennis.pojos.PageResult;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


public class PageUtil {

    /**
     * {@link PageRequest} to {@link Page}
     */
    public static Page convert(PageRequest pageRequest) {
        return new Page(pageRequest.getPage(), pageRequest.getPageSize());
    }

    /**
     * {@link Page} to {@link PageResult}
     */
    public static PageResult convert(Page page) {
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * {@link Page} to {@link PageResult}
     * 使用BeanCopyUtils
     * 将PageResult的泛型转为另一个泛型
     */
    public static <TARGET, ORIGINAL> PageResult<TARGET> convert(Page<ORIGINAL> page, Class<TARGET> targetClass) {
        page.convert(each -> BeanCopyUtils.copyBean(each, targetClass));
        return convert(page);
    }

    /**
     * {@link Page} to {@link PageResult}
     * 使用特定方法
     * 将PageResult的泛型转为另一个泛型
     */
    public static <TARGET, ORIGINAL> PageResult<TARGET> convert(Page<ORIGINAL> page, Function<? super ORIGINAL, ? extends TARGET> mapper){
        List<TARGET> targetDataList = page.getRecords().stream()
                .map(mapper)
                .collect(Collectors.toList());
        return new PageResult(page.getTotal(),targetDataList);
    }
}
